﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Ha666.Common;
using Top.Api.Util;

namespace Ha666.WebAPI
{
    public class ApiKeyHandler : DelegatingHandler
    {
        private static readonly string v = ConfigurationManager.AppSettings["v"];
        private static string[] WhiteList = { "GetTime" };
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string response = ValidateKey(request.RequestUri);
            if (response != "")
            {
                var tsc = new TaskCompletionSource<HttpResponseMessage>();
                tsc.SetResult(new HttpResponseMessage(HttpStatusCode.Forbidden) { ReasonPhrase = HttpUtility.UrlEncode(response) });
                return tsc.Task;
            }
            return base.SendAsync(request, cancellationToken);
        }

        private string ValidateKey(Uri url)
        {
            NameValueCollection request = HttpContext.Current.Request.Form;
            if (request.Count < 4)
                return "系统参数不能为空";
            if (request["appkey"] == null)
                return "appkey参数不能为空";
            if (request["v"] == null)
                return "v参数不能为空";
            bool isexist = WhiteList.Any(white => url.ToString().Contains(white));
            if (!isexist)
            {
                if (request["time"] == null)
                    return "time参数不能为空";
                if (request["time"].Length != 19)
                    return "time参数错误";
                DateTime min;
                DateTime.TryParse(request["time"], out min);
                double timeDifference = DateTime.Now.Subtract(min).TotalSeconds;
                if (timeDifference > 180 || timeDifference < -180)
                    return "请调整本机时间后重试";
            }
            if (request["sign"] == null)
                return "sign参数不能为空";
            if (!request["appkey"].Equals(APIServices.API_APP_KEY))
                return "appkey参数错误";
            if (!request["v"].Equals(v))
                return "v参数错误";
            var dictionary = request.Keys.Cast<string>().Where(key => !key.Equals("sign")).ToDictionary(key => key, key => request[key]);
            if (!request["sign"].Equals(TopUtils.SignTopRequest(dictionary, APIServices.API_APP_SECRET)))
                return "签名错误";
            return "";
        }
    }
}